package com.amentretenimiento;

import java.net.URL;
import java.util.Calendar;
import java.util.List;
import java.util.Vector;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Consulta extends ListActivity {
//	String urlamentretenimiento="http://201.155.80.190:8080/";
//	private String urlamentretenimiento="http://201.155.80.190:1863/";
	private String urlamentretenimiento=UsuariosSQLiteHelper.urlam;

//	String urlamentretenimiento="http://www.smartthinking.com.mx:8080/";


	Bundle extras;
	SAXParserFactory spf;
	SAXParser sp;
	XMLReader xr ;
	int ruta;
	LoginSitesList loginsitesList = null;
	private LayoutInflater mInflater;
	private Vector<RowData> data;
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// TODO Coloque su código aquí
		setContentView(R.layout.consul);	
		
		//Checar intenet
		boolean internet = isInternetConnectionActive(Consulta.this);
		if (internet == true){
		
		Bundle extras=getIntent().getExtras();
		if(extras!=null){
			
//			String nombre=extras.getString("nombre");
			mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
	        data = new Vector<RowData>();
	        
			String idAgente=extras.getString("idagente");
			loginsitesList=mostrarInfo( idAgente);
//			Toast.makeText(getApplicationContext(), ""+loginsitesList.getidCliente().get(0).toString(), Toast.LENGTH_SHORT).show();

			for (int i = 0; i < loginsitesList.getnombre().size(); i++) {
				RowData rd = new RowData(""+loginsitesList.getnombre().get(i),""+loginsitesList.getidCliente().get(i) );
		        data.add(rd);
			}
			}
		CustomAdapter adapter = new CustomAdapter(this, R.layout.custom_row2,R.id.item, data);
        setListAdapter(adapter);  
		} else if(internet == false){
//			Toast.makeText(getApplicationContext(), "Necesitas conexión a internt", Toast.LENGTH_LONG).show();
            AlertDialog alertdialog=new AlertDialog.Builder(Consulta.this).create();
			alertdialog.setIcon(R.drawable.icon);
	    	alertdialog.setTitle("Aviso");
	    	alertdialog.setMessage("Error de conectividad");
	    	alertdialog.show();
     		}
		}
	
	protected LoginSitesList mostrarInfo(String IdAgente) {
     		LoginSitesList loginsitesList = null;
			int dia;
			Calendar cal=Calendar.getInstance();
			dia=cal.get(Calendar.DAY_OF_WEEK);
			if(dia==1){
				dia=7;
			}else{
				dia=(cal.get(Calendar.DAY_OF_WEEK)-1);
			}
			
			try {
				
				/** Handling XML */
				spf = SAXParserFactory.newInstance();
				sp = spf.newSAXParser();
				xr = sp.getXMLReader();
	
				/** Send URL to parse XML Tags */
				URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?Query=select*from+ruta+where+idagente="+IdAgente+"and+dia="+dia);
				
				Log.i("MII TAGG", ""+sourceUrl);
	
				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
				LoginMyXMLHandler myXMLHandler = new LoginMyXMLHandler();
				xr.setContentHandler(myXMLHandler);
				xr.parse(new InputSource(sourceUrl.openStream()));
				
			} catch (Exception e) {
				System.out.println("XML Pasing Excpetion = " + e);
			}
			loginsitesList = LoginMyXMLHandler.loginsitesList;
			
//			Toast.makeText(getApplicationContext(), ""+loginsitesList.getIdRuta().get(0).toString(), Toast.LENGTH_SHORT).show();
			
			
			ruta= Integer.parseInt(loginsitesList.getIdRuta().get(0).toString()); 
			
			
			try {
				
				/** Handling XML */
				spf = SAXParserFactory.newInstance();
				sp = spf.newSAXParser();
				xr = sp.getXMLReader();
	
				/** Send URL to parse XML Tags */
				
				
				
				
				URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?Query=select+idcia,idruta,a.idcliente,b.numsucursal,b.nombre,secuencia,hora,ttranslado+from+itinerario+a+inner+join+cliente+b+on+a.idcliente=b.idcliente+where+idruta="+ruta+"order+by+secuencia");
				
				Log.i("MII TAGG", ""+sourceUrl);
	
				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
				LoginMyXMLHandler myXMLHandler = new LoginMyXMLHandler();
				xr.setContentHandler(myXMLHandler);
				xr.parse(new InputSource(sourceUrl.openStream()));
				
			} catch (Exception e) {
				System.out.println("XML Pasing Excpetion = " + e);
			}
			loginsitesList = LoginMyXMLHandler.loginsitesList;
			
//			Toast.makeText(getApplicationContext(), ""+loginsitesList.getnumSucursal().get(0).toString(), Toast.LENGTH_SHORT).show();
//			Toast.makeText(getApplicationContext(), ""+loginsitesList.getidCliente().get(0).toString(), Toast.LENGTH_SHORT).show();
//			Toast.makeText(getApplicationContext(), ""+loginsitesList.getnombre().get(0).toString(), Toast.LENGTH_SHORT).show();

			
			
			
		
		
		
		String result;
		result=""+ruta+"@@@"+loginsitesList.getidCliente().get(0).toString();
		return loginsitesList;
		
		
	}

	
	public void onListItemClick(ListView parent, View v, int position, long id) {
	   //Checar internet
		boolean internet = isInternetConnectionActive(Consulta.this);
		if (internet == true){
		
		CustomAdapter adapter = (CustomAdapter) parent.getAdapter();
	    
			
	        Intent nd = new Intent(Consulta.this, Detalle.class);
	        
	        nd.putExtra("idcliente", loginsitesList.getidCliente().get(position).toString().trim());
	        
//	        Toast.makeText(getApplicationContext(), ""+loginsitesList.getidCliente().get(position).toString().trim(), Toast.LENGTH_LONG).show();
	        
	        startActivity(nd);
		}else if(internet == false){
//			Toast.makeText(getApplicationContext(), "Necesitas conexión a internt", Toast.LENGTH_LONG).show();
            AlertDialog alertdialog=new AlertDialog.Builder(Consulta.this).create();
			alertdialog.setIcon(R.drawable.icon);
	    	alertdialog.setTitle("Aviso");
	    	alertdialog.setMessage("Error de conectividad");
	    	alertdialog.show();
     		}
	}
	
	private class RowData {
	    protected String mItem;
	        protected String mDescription;

	        RowData(String item, String description){
	        mItem = item;
	        mDescription = description;             
	    }

	        @Override
	        public String toString() {
	                return mItem + " " +  mDescription;
	        }
	}
	
	private class CustomAdapter extends ArrayAdapter<RowData> {

        public CustomAdapter(Context context, int resource,
                        int textViewResourceId, List<RowData> objects) {
                super(context, resource, textViewResourceId, objects);

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder = null;

                //widgets displayed by each item in your list
                TextView item = null;
                TextView description = null;

                //data from your adapter
                RowData rowData= getItem(position);


                //we want to reuse already constructed row views...
                if(null == convertView){
                        convertView = mInflater.inflate(R.layout.custom_row2, null);
                        holder = new ViewHolder(convertView);
                        convertView.setTag(holder);
                }
                // 
                holder = (ViewHolder) convertView.getTag();
                item = holder.getItem();
                item.setText(rowData.mItem);
                item.setTextSize(18);
    			item.setTextColor(Color.BLACK);

                description = holder.getDescription();          
                description.setText(rowData.mDescription);
                description.setTextSize(16);
    			description.setTextColor(Color.BLACK);

                return convertView;
        }
}

/**
 * Wrapper for row data.
 *
 */
private class ViewHolder {      
    private View mRow;
    private TextView description = null;
    private TextView item = null;

        public ViewHolder(View row) {
        mRow = row;
        }

        public TextView getDescription() {
                if(null == description){
                        description = (TextView) mRow.findViewById(R.id.item);
                }
                return description;
        }

        public TextView getItem() {
                if(null == item){
                        item = (TextView) mRow.findViewById(R.id.description);
                }
                return item;
        }       
    }
public static boolean isInternetConnectionActive(Context context) {
	 boolean bool = false;

	   NetworkInfo networkInfo = ((ConnectivityManager) context
             .getSystemService(Context.CONNECTIVITY_SERVICE))
             .getActiveNetworkInfo();

           if(networkInfo == null || !networkInfo.isConnected()) {
            return false;
           }
           return true;
}
	
	
}
